//提取获取所以菜单、获取一级菜单的逻辑
import type { MenuItem, CreateOrEditMenu } from '@/api/menus'
import { saveOrUpdate, getAll, deleteMenu } from '@/api/menus'
import router from '@/router/index'

//最外面包裹一层函数
export async function useMenus() {
  //1.保存所有菜单的数据
  const allMenus = ref([] as MenuItem[])

  //2. 获取所以菜单的数据的函数
  const getAllMenus = async () => {
    const { data } = await getAll()
    if (data.code === '000000') {
      allMenus.value = data.data
    } else {
      ElMessage.error('获取菜单列表信息失败！')
      throw new Error('获取菜单列表信息失败！')
    }
  }
  //3.获取一级菜单的函数
  const topMenus = computed(() => allMenus.value.filter((menu) => menu.level === 0))
  //4.表单的响应式数据
  const form = ref<CreateOrEditMenu>({
    name: '',
    href: '',
    parentId: -1,
    description: '',
    icon: '',
    shown: true,
    orderNum: 0
  })

  //5.封装提交表单的事件处理
  const onSubmit = async () => {
    const { data } = await saveOrUpdate(form.value)
    if (data.code === '000000' && data.data) {
      ElMessage.error('添加菜单成功！')
      router.push({ name: 'menus' })
    } else {
      ElMessage.error('添加菜单失败！')
      throw new Error('添加菜单失败！')
    }
  }

  //6.删除事件
  const handleDelete = async (id: string) => {
    await ElMessageBox.confirm('确认要删除吗？', '删除提醒', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).catch(() => {
      ElMessage.info('删除操作被取消')
      return new Promise(() => {})
    })
  }

  //7.调用删除接口函数
  const { data } = await deleteMenu(id)
  if (data.code === '000000' && data.data) {
    ElMessage.success('删除菜单成功！')
    getAllMenus()
  } else {
    ElMessage.error('删除菜单失败！')
    throw new Error('删除菜单失败！')
  }

  return {
    allMenus,
    topMenus,
    getAllMenus,
    onSubmit,
    form,
    handleDelete
  }
}
